/*
 * @Date: 2023-03-12 13:43:48
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-12 14:41:19
 * @FilePath: \A19\backend\src\api\Experiment\ApiGetUserExps.ts
 */
import { ApiCall } from "tsrpc";
import { ReqGetUserExps, ResGetUserExps } from "../../shared/protocols/Experiment/PtlGetUserExps";
import { Global } from '../../Global/index';
import { users } from "../../shared/types/user";
import { codeAnswer } from "../../shared/types/userExperiments";
import { ObjectId } from "mongodb";

export default async function (call: ApiCall<ReqGetUserExps, ResGetUserExps>) {
    // TODO
    const { experiment,student } = call.req
    if(experiment && student){
        const ret = await Global.collection('userExperiments').findOne({
            student,
            experiment
        })

        return call.succ({
            exp:ret
        })
    }

    if(student){
        const ret = await Global.collection('userExperiments').find({
            student
        }).toArray()
        return call.succ({
            exps: ret.map(exp => exp.experiment)
        })
    }

    if(experiment){
        const ret = await Global.collection('userExperiments').aggregate([
            {
                $match:{
                    experiment
                }
            },
            {
                $lookup:{
                    from: "users",
                    localField: "student",
                    foreignField: "_id",
                    as: "student"
                }
            }
        ]).toArray()
        return call.succ({
            commitedUserExps: ret as {
                _id: ObjectId;
                student: users[];
                experiment: ObjectId;
                submitTime: Date;
                score: number;
                answers: codeAnswer[];
            }[]
        })
    }
    
}